<template>
  <div v-if="isShow" ref="chart" style="height: 100%"></div>
  <!-- <custom-no-data-vue v-else></custom-no-data-vue> -->
  <p v-else class="no-data height-full d-flex flex-a-c flex-ju-c">暂无数据</p>
</template>

<script>
import * as echarts from 'echarts';
import chinaMap from '@/assets/json/china_map.json'

/**
 * @desc 获取echarts实例
 * @param { HTMLElement } ele html元素
 * @returns { Object } echarts 实例
 */
export const getEchartsInstance = ele => {
  const existInstance = echarts.getInstanceByDom(ele)
  const echartsInstance = existInstance || echarts.init(ele)
  return echartsInstance
}

export default {
  name: 'CustomChart',
  props: {
    isShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      control: null,
      echartsInstance: null,
    }
  },
  methods: {
    renderChart(options, notMerge = false) {
      if (!this.$refs['chart'] || !this.isShow) return
      if (options.geo) {
        echarts.registerMap('china', { geoJSON: chinaMap })
      }
      this.echartsInstance = getEchartsInstance(this.$refs['chart'])
      this.echartsInstance.clear()
      this.echartsInstance.setOption(options, notMerge)

      if (this.control) return
      this.control = new AbortController()
      window.addEventListener('resize', this.handleResize, {
        signal: this.control.signal,
      })
    },
    handleResize() {
      this.echartsInstance && this.echartsInstance.resize()
    },

    getChartInstance() {
      return this.echartsInstance
    }
  },
  beforeDestroy() {
    this.echartsInstance && this.echartsInstance.dispose()
    this.control && this.control.abort()
  },
}
</script>
